<template>
  <view :style="DynamicHeight">
    <!-- 导航栏 -->
    <u-navbar title="考勤打卡" @leftClick="back"></u-navbar>
    <!-- loading -->
    <zero-loading class="zeroLoading" v-if="loading" type="radar" maskOpacity="1" zIndex="9"></zero-loading>
    <view style="width: 100vw;height: 100%;overflow-y: auto;">
      <!-- APP端使用原生地图 -->
      <!-- #ifdef APP-PLUS -->
      <view id="map" :style="{ height: Mapheight }" :mapData="mapData" :change:mapData="mapDom.dataChange"></view>
      <!-- #endif -->

      <!-- H5端使用高德地图 -->
      <!-- #ifdef H5 -->
      <view id="mapContainer" :style="{ height: Mapheight }"></view>
      <web-view id="my-webview" ref="webview" :src="hwUrl" @message="handleMessage" style="width: 0;"
        :style="{ height: Mapheight }"></web-view>
      <!-- #endif -->

      <view class="waiqin-card">
        <!-- 重新获取定位图标 -->
        <!-- #ifdef APP-PLUS -->
        <view class="relocation" @click="setLocation">
          <image src="@/static/icon/dingwei2.svg"></image>
        </view>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <view class="relocation" @click="hwswtLocation">
          <image src="@/static/icon/dingwei2.svg"></image>
        </view>
        <!-- #endif -->
        <view class="clock-label">我的位置</view>
        <view class="clock-address">{{ userPost.address.poiName }}</view>
        <view class="clock-timeArea">员工打卡时间范围：{{ kaoqinInfo.start_clock_time }}-{{ kaoqinInfo.end_clock_time }}</view>
        <view class="clock-container-top">
          <!-- 上班打卡区域 -->
          <view class="clock-onoff-box">
            <view class="clock-time">上班{{ kaoqinInfo.start_time }}</view>
            <view class="clock-msg" v-if="onClockValue.clock_time != null">
              <u-icon v-if="onClockValue.clock_status == 1" name="checkmark-circle-fill" color="#2979ff"
                size="16"></u-icon>
              <u-icon v-else name="info-circle-fill" color="#f9ae3d" size="16"></u-icon>
              <text>{{ onClockValue.clock_status == 1 ? '上班打卡' : '迟到打卡' }}{{ format(onClockValue.clock_time) }}</text>
            </view>
            <view class="clock-msg" v-else><text>未打卡</text></view>
          </view>

          <!-- 下班打卡区域 -->
          <view class="clock-onoff-box">
            <view class="clock-time">下班{{ kaoqinInfo.end_time }}</view>
            <view class="clock-msg" v-if="offClockValue.clock_time != null">
              <u-icon v-if="offClockValue.clock_status == 1" name="checkmark-circle-fill" color="#2979ff"
                size="16"></u-icon>
              <u-icon v-else name="info-circle-fill" color="#f9ae3d" size="16"></u-icon>
              <text>{{ offClockValue.clock_status == 1 ? '下班打卡' : '早退打卡' }}{{ format(offClockValue.clock_time) }}</text>
            </view>
            <view class="clock-msg" v-else><text>未打卡</text></view>
          </view>
        </view>
        <up-button :disabled="disabledBtn || loading || !addressReady" style="margin-top: 24rpx;" @click="onClock"
          type="primary"
          :text="`${showTime}${isInPost == 1 ? '' : '外勤'}${clock_type == 1 ? '上班' : '下班'}打卡`"></up-button>
      </view>
    </view>

    <!-- 早退迟到提醒 custom-->
    <!-- <tui-modal :button="button" :show="modalShow" @click="modalClick" @cancel="modalShow = false" title="提示"
      :content="content"> </tui-modal> -->

    <!-- 早退迟到提醒-->
    <tui-modal :show="modalShow" custom>
      <view class="custom-modal">
        <view class="modal-title">
          提示
        </view>
        <view class="modal-content">
          {{ content }}
        </view>
        <view class="input-section" v-if="isInPost == 2 && Isitabusinesstrip == 0"
          style="border: 1px solid #ccc;border-radius: 5px;padding: 5px;">
          <input class="modal-input" v-model="inputValue" placeholder="请输入外勤备注（必填）" @input="validateInput" />
          <view class="error-message" v-if="showError">
            请填写外勤原因！
          </view>
        </view>

        <view class="modal-buttons">
          <view class="modal-button cancel-button" @click="modalShow = false">
            取消
          </view>
          <view class="modal-button confirm-button" @click="modalClick">
            确定
          </view>
        </view>
      </view>
    </tui-modal>

    <!-- 消息提示	 -->
    <u-toast ref="uToast" />

    <!-- 打卡成功提示 -->
    <tui-modal :show="successShow" custom>
      <view class="tui-modal-custom">
        <view class="close" @click="successShow = false">
          <up-icon name="close-circle-fill" size="20"></up-icon>
        </view>
        <image mode="widthFix" src="/static/face/success.png"></image>
        <view class="success">
          <view>
            <up-icon name="checkmark-circle-fill" color="#02B045" size="16"></up-icon>
          </view>
          <text style="margin-left: 14rpx;">{{ successMsg }}打卡成功</text>
        </view>
        <view class="time">打卡时间：{{ successTime }}</view>
        <view class="btn" @click="toStatis">查看打卡结果</view>
      </view>
    </tui-modal>

    <!-- 底部导航栏 -->
    <u-tabbar :value="tabbarIndex" :placeholder="true">
      <u-tabbar-item text="打卡" icon="map"></u-tabbar-item>
      <u-tabbar-item @click="toStatis" text="统计" icon="file-text"></u-tabbar-item>
      <u-tabbar-item @click="settingSetUp" text="设置" icon="setting"></u-tabbar-item>
    </u-tabbar>
  </view>
</template>

<script>

import clockApi from "@/apis/cloud/clock.js"
import { Kaoqinisfirstrlsb } from '@/apis/worKspace/face.js'
import { useClockStore, useUserStore } from '@/pinia-store/user'
import { calcCoordsDistance } from '@/utils/location'
// #ifdef H5
import AMapLoader from "@amap/amap-jsapi-loader"
// #endif
import dayjs from 'dayjs'
import { mapStores } from 'pinia'

// H5端使用高德地图
// #ifdef H5
window._AMapSecurityConfig = {
  securityJsCode: "6a3b0ae034d75c523abf64e1a334791e" // 设置你的安全密钥
};
// #endif

export default {
  data () {
    return {
      userClockMsg: true,
      hwUrl: '/hybrid/html/local.html',
      // APP端使用
      mapData: null, // render交互
      map: null, // 地图实例
      pos: null, // 经纬度坐标
      // H5端使用
      // #ifdef H5
      AMap: null,
      marker: null,
      circle: null,
      // #endif
      loading: true,
      tabbarIndex: 0, //底部导航栏索引
      showTime: '',
      taday: null,
      t: null, // 定时器属性
      clock_type: null,
      isInPost: null,
      successShow: false,
      successMsg: '',
      successTime: '',
      onClockValue: {
        clock_type: null,
        clock_time: null,
        clock_status: null
      },
      offClockValue: {
        clock_type: null,
        clock_time: null,
        clock_status: null
      },
      amEndTime: null,
      startTime: null,
      clcok_type: null,
      endTime: null,
      modalShow: false,
      content: '',
      clockParams: {},
      button: [
        {
          text: "取消",
          plain: true
        },
        {
          text: "确定",
          type: "primary",
          plain: false
        }
      ],
      kaoqinInfo: {
        lat: 0,
        long: 0,
        clock_up: "08:30",
        clock_down: "17:30",
        group_id: 9
      },
      disabled: true,
      userPost: {
        lat: 0,
        long: 0,
        address: {
          poiName: ''
        }
      },
      user: {
        img_url: '',
        worker_name: '',
      },
      hwvw: null,
      isfirstrlsbstatus: null, // 人脸图片状态
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      scrollViewHeight: {}, // 动态计算 scroll-view 的高度
      Mapheight: 0,
      userGroupMsg: {},
      inputValue: '',
      showError: false,
      isValid: false,
      Isitabusinesstrip: 0,
      addressReady: false,
      height: 0, // 高度
      DynamicHeight: {}, // 动态高度
      qingjiaObj:{}
    };
  },
  created () {
    // 重置打卡相关数据
    this.addressReady = false
    this.userPost = {
      lat: 0,
      long: 0,
      address: { poiName: '' }
    }
    this.isInPost = null
    this.clock_type = null
    this.showTime = ''
    this.onClockValue = { clock_type: null, clock_time: null, clock_status: null }
    this.offClockValue = { clock_type: null, clock_time: null, clock_status: null }
    this.inputValue = ''
    this.showError = false
    this.modalShow = false
    this.successShow = false
    this.successMsg = ''
    this.successTime = ''

    this.height = (uni.getSystemInfoSync().windowHeight || uni.getSystemInfoSync().screenHeight) || 0
    // #ifdef APP-PLUS
    this.DynamicHeight = { height: `${this.height - 52}px`, overflow: 'hidden' }
    // #endif
    // #ifdef H5
    this.DynamicHeight = { height: `${this.height - 52}px`, overflow: 'hidden' }
    // #endif

    // #ifdef APP-PLUS
    this.Mapheight = `${this.height / 1.65}px`
    // #endif

    // #ifdef H5
    this.Mapheight = `${this.height / 1.98}px`
    // #endif
    uni.$off('backisfirstrlsbstatus')
    this.getisfirstrlsb()
  },
  mounted () {
    this.taday = dayjs().format('YYYY-MM-DD');
    this.t = setTimeout(() => this.time(), 1000);
    this.user = this.userStore.user ? this.userStore.user : { img_url: null, worker_name: '张三' };
    this.setKaoqinInfo(false);

    // #ifdef H5

    this.AMap = null
    window.addEventListener("message", this.handleMessage);

    // #endif
  },
  beforeDestroy () {
    // #ifdef H5
    // 移除事件监听
    window.removeEventListener('message', this.handleMessage);
    // #endif
  },
  onLoad () {
    // #ifdef H5
    window.addEventListener('message', this.handleMessage, false);
    // #endif
    uni.$on('back', (data) => {
      this.taday = dayjs().format('YYYY-MM-DD');
      this.t = setTimeout(() => this.time(), 1000);
      this.user = this.userStore.user ? this.userStore.user : { img_url: null, worker_name: '' };
      this.setKaoqinInfo(false, true);
    });

    uni.$on('backisfirstrlsbstatus', () => {
      this.getisfirstrlsb()
    })
  },
  computed: {
    ...mapStores(useUserStore, useClockStore),
    disabledBtn () {
      // 接口返回不允许
      if (!this.userClockMsg || this.userGroupMsg?.flag != 1) {
        return true;
      }
      // 经纬度无效（0 / null / undefined）
      if (!this.userPost || this.userPost.lat === 0 || this.userPost.long === 0) {
        return true;
      }
      return false;
    }
  },
  methods: {
    validateInput () {
      this.isValid = this.inputValue.trim().length > 0
      this.showError = false
    },
    async getisfirstrlsb () {
      try {
        let res = await Kaoqinisfirstrlsb({
          'phone': this.userStore.user.phone,
        })
        if (res.status == 1) {
          this.isfirstrlsbstatus = res.status
        } else if (res.status == 0) {
          this.isfirstrlsbstatus = res.status
        }

      } catch (e) {

      }
    },
    // 处理从 local.html 接收的经纬度
    handleMessage (event) {

      if (event.data && event.data.type === 'locationUpdate') {
        try {
          // H5端初始化高德地图
          const data = JSON.parse(event.data.params); // UniApp 的 @message 数据格式

          this.pos = data;

          // 如果地图已初始化，更新位置
          if (!this.AMap) {
            this.loadAMap()
              .then(() => {
                // 地图加载完成后执行定位
                this.hwswtLocationCallback(data);
              })
              .catch((error) => {
                console.error("地图加载失败:", error);
              });
          } else {
            // 地图已初始化，执行定位
            this.hwswtLocationCallback(data);
          }


        } catch (error) {
          console.error('Failed to parse position:', error);
        }
      }

    },
    loadAMap () {
      return new Promise((resolve, reject) => {
        if (this.AMap) {
          // 如果地图已经加载，直接 resolve
          resolve();
          return;
        }

        AMapLoader.load({
          key: "c9c069d05cb4075e3e24aefea6f77b85", // 高德key
          version: "2.0",
          plugins: ["AMap.Geolocation", "AMap.Circle", "AMap.Marker"],
        })
          .then((AMap) => {
            this.AMap = AMap;
            this.map = new AMap.Map("mapContainer", {
              viewMode: "3D",
              zoom: 10,
            });
            this.loading = false
            // 地图加载完成后 resolve
            resolve();
          })
          .catch((e) => {
            console.error("高德地图加载失败:", e);
            uni.$u.toast("地图加载失败");
            this.loading = false;
            reject(e); // 拒绝 Promise
          });
      });
    },
    format (date) {
      return dayjs(date).format('HH:mm:ss')
    },
    setClockBtn () {
      const now = new Date().getTime();
      // 上午已打卡 或过午间
      if (this.onClockValue.clock_time != null || now > this.amEndTime) {
        this.clock_type = 2;
        return '下班打卡'
      } else {
        this.clock_type = 1;
        return '上班打卡'
      }
    },
    time () {
      clearTimeout(this.t); //清除定时器
      this.t = setTimeout(() => this.time(), 1000); //设定定时器，循环运行
      this.showTime = dayjs().format('HH:mm:ss');

      const now = new Date().getTime();
      // 上午已打卡 或过午间
      if (this.onClockValue.clock_time != null || now > this.amEndTime) {
        this.clock_type = 2;
        return '下班打卡'
      } else {
        this.clock_type = 1;
        return '上班打卡'
      }
    },
    setLocation (reload) {
      if (reload) {
        this.loading = true;
      }
      const that = this;

      // 清除当前定位数据
      this.userPost = {
        lat: 0,
        long: 0,
        address: { poiName: '' }
      };
      this.isInPost = null;
      // APP端使用uni.getLocation
      uni.getLocation({
        type: 'gcj02', // 坐标系类型
        geocode: true,
        success: function (res) {
          that.userPost = res;
          that.userPost.long = res.longitude;
          that.userPost.lat = res.latitude;
          that.isInPost = calcCoordsDistance(that.kaoqinInfo, that.userPost, that.kaoqinInfo.range) ? 1 : 2;

          const data = {
            kaoqinInfo: that.kaoqinInfo,
            userPost: that.userPost,
            ts: Date.now()
          }
          // that.mapData = JSON.stringify(data)
          // 等定位完成后再更新地图和按钮状态
          that.mapData = JSON.stringify({ kaoqinInfo: that.kaoqinInfo, userPost: that.userPost, ts: Date.now() });

          setTimeout(() => {
            that.loading = false;
          }, 1000)
        },
        fail: function (res) {
          setTimeout(() => { that.loading = false; }, 1000)
          that.loading = false;
          console.log('获取定位失败：' + res.errMsg);
        }
      });

    },
    hwswtLocation (data) {

      this.loading = true;

      uni.$u.toast("正在重新获取定位...");

      // 清除当前定位数据
      this.userPost = {
        lat: 0,
        long: 0,
        address: { poiName: '' }
      };
      this.isInPost = null;

      // 清空地图
      if (this.map) {
        this.map.clearMap();
      }

      // 请求 local.html 重新获取定位
      const iframe = window.frames[0];

      if (iframe) {
        iframe.postMessage({
          type: 'forceRelocate',
        }, '*');
      } else {
        console.warn('iframe not found');
      }



    },
    hwswtLocationCallback (data) {

      const that = this;

      if (!this.AMap) {
        uni.$u.toast("地图尚未加载完成");
        return;
      }

      this.map.clearMap();
      this.marker = null;
      this.circle = null;

      const lng = parseFloat(data[0]);
      const lat = parseFloat(data[1]);

      if (isNaN(lng) || isNaN(lat)) {
        uni.$u.toast("定位数据无效，请重试");
        console.error("Invalid location data:", data);
        this.loading = false;
        return;
      }

      this.userPost = {
        long: lng,
        lat: lat,
        address: { poiName: '' }
      };

      this.isInPost = calcCoordsDistance(this.kaoqinInfo, this.userPost, this.kaoqinInfo.range) ? 1 : 2;

      // 创建圆形区域
      var circle = new AMap.Circle({
        center: [this.kaoqinInfo.long, this.kaoqinInfo.lat],
        radius: this.kaoqinInfo.range,
        fillOpacity: 0.1,
        strokeDasharray: [10, 10],
        fillColor: "#1791fc",
        zIndex: 50
      });

      this.map.add(circle);

      // 获取地址信息
      AMap.plugin('AMap.Geocoder', () => {
        const geocoder = new AMap.Geocoder({ city: "全国" });
        geocoder.getAddress([lng, lat], (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.userPost.address.poiName = result.regeocode.formattedAddress || '未知位置';
            this.addressReady = true;
            this.$forceUpdate();
          } else {
            this.userPost.address.poiName = '未知位置';
          }
        });
      });

      // 创建 marker
      const icon = new AMap.Icon({
        size: new AMap.Size(25, 34),
        image: 'https://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png',
        imageSize: new AMap.Size(15, 20)
      });

      const marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        offset: new AMap.Pixel(-7, -20),
        icon: icon
      });

      this.map.add(marker);
      this.map.setFitView([marker]);

      this.loading = false;

    },
    async setKaoqinInfo (reload, isBack) {
      // 先获取考勤组
      const userGroupMsg = await clockApi.getLongLat({ depart_id: this.user.depart_id, worker_id: this.user.worker_id });
      const tempClock = await clockApi.ClicktempClock({ worker_id: this.user.worker_id }); // 获取出差单接口
      // this.Isitabusinesstrip = tempClock.data  // 是否出差 0 是无 1是有
      const data = tempClock.data || 0; // 防止 data 为 null 或 undefined
      // 请假对象
      this.qingjiaObj = (data && data.qingjia) ? data.qingjia : null;
      // 是否出差
      this.Isitabusinesstrip = (data && data.chuchai !== undefined) ? data.chuchai : data;
      if (userGroupMsg.status != 1) {
        uni.$u.toast(userGroupMsg.msg);
        this.userClockMsg = false;
        this.userGroupMsg = null;
        this.loading = false;
        return
      }
      this.userClockMsg = true;  // 表示接口校验通过
      this.userGroupMsg = userGroupMsg; // 保存接口返回
      this.kaoqinInfo = userGroupMsg.data;
      // 判断上下班按钮展示
      this.amEndTime = new Date(`${this.taday} ${this.kaoqinInfo.am_end_time}`.replace(/-/g, '/')).getTime();
      this.startTime = new Date(`${this.taday} ${this.kaoqinInfo.start_time}`.replace(/-/g, '/')).getTime();
      this.endTime = new Date(`${this.taday} ${this.kaoqinInfo.end_time}`.replace(/-/g, '/')).getTime();
      // this.endTime = new Date(`2025-04-21 ${this.kaoqinInfo.end_time}`).getTime();
      let nowTime = new Date().getTime();

      // 获取打卡记录
      const isClockMsg = await clockApi.getClockRecord({
        worker_id: this.user.worker_id
      })

      this.status = isClockMsg.status;
      const clockNum = isClockMsg.data.length;
      // 回显上下班打卡记录
      isClockMsg.data.forEach((item, index) => {
        const recordTime = new Date(item.clock_time.replace(/-/g, '/')).getTime();

        // 第0条
        if (index == 0) {
          if (item.attend_type == 'Outside') {
            // 外勤需判断打卡时间
            this.setWaiqin(item, recordTime);
          } else {
            if (item.clock_type == 1) {
              this.onClockValue = item;
              const startLimit = this.startTime + 60 * 1000;
              this.onClockValue.clock_status = recordTime <= startLimit ? 1 : 2;
            } else if (item.clock_type == 2) {
              this.offClockValue = item;
              this.offClockValue.clock_status = this.endTime < recordTime ? 1 : 2;
            }
          }
          return;
        }

        // 最后一条
        if (index == clockNum - 1) {
          if (item.attend_type == 'Outside') {
            // 外勤需判断打卡时间
            this.setWaiqin(item, recordTime);
          } else {
            if (item.clock_type == 1) {
              this.onClockValue = item;
              const startLimit = this.startTime + 60 * 1000; // 上班时间 +1 分钟
              this.onClockValue.clock_status = recordTime <= startLimit ? 1 : 2;
            } else if (item.clock_type == 2) {
              this.offClockValue = item;
              this.offClockValue.clock_status = this.endTime < recordTime ? 1 : 2;
            }
          }
        }
      });

      // 打卡成功返回查询
      if (isBack) {
        // successMsg
        const attend_type = this.clockStore.clock.attend_type;
        const type = this.clockStore.clock.clock_type;
        this.successTime = type == 1 ? this.onClockValue.clock_time : this.offClockValue.clock_time;
        if (attend_type == 'Outside') {
          this.successMsg = `外勤${type == 1 ? '上班' : '下班'}`
        } else {
          this.successMsg = `${type == 1 ? '上班' : '下班'}`
        }
        this.successShow = true;
      }
      if (!reload) {
        // 获取定位
        // #ifdef APP-PLUS
        this.setLocation();
        // #endif

        // #ifdef H5
        // this.hwswtLocation()
        // #endif
      }
    },
    // 外勤记录判断
    setWaiqin (record, recordTime) {
      if (record.clock_type == 1) {
        this.onClockValue = record;
        this.onClockValue.clock_status = this.startTime > recordTime ? 1 : 2;
      } else if (record.clock_type == 2) {
        this.offClockValue = record;
        this.offClockValue.clock_status = this.endTime < recordTime ? 1 : 2;
      }
      // if (this.amEndTime > recordTime) {
      //   this.onClockValue = record;
      //   this.onClockValue.clock_status = this.startTime > recordTime ? 1 : 2;
      // } else {
      //   this.offClockValue = record;
      //   this.offClockValue.clock_status = this.endTime < recordTime ? 1 : 2;
      // }
    },
    modalClick () {
      // 外勤且没有出差单 -> 必填备注
      if (this.isInPost == 2 && this.Isitabusinesstrip == 0) {
        if (!this.inputValue.trim()) {
          this.showError = true
          return
        }
      }
      this.addClock()
    },
    // 添加打卡记录
    async addClock () {
      if (!this.userPost.address.poiName || this.userPost.lat === 0 || this.userPost.long === 0) {
        uni.$u.toast('定位未完成，请稍后重试');
        return;
      }

      if (!this.addressReady) {
        uni.$u.toast('地址还在获取，请稍后打卡')
        return
      }

      let setclocktype = this.clock_type

      if(this.qingjiaObj && this.qingjiaObj.time_type){
        setclocktype = this.qingjiaObj.time_type == '3' ? 1 : this.qingjiaObj.time_type == '2' ? 2  : this.clock_type;
      }


      // 符合打卡时间进入人脸识别页面 缓存打卡信息
      this.clockParams = {
        worker_id: this.user.worker_id,
        phone: this.user.phone,
        location: this.userPost.address.poiName,
        lnglat: `[${this.userPost.long},${this.userPost.lat}]`,
        // clock_type: this.isInPost == 1 ? this.clock_type : 3,// 外勤不根据时间判断
        // clock_type: this.clock_type,// 外勤不根据时间判断
        clock_type: setclocktype,// 外勤不根据时间判断
        bm_id: this.user.depart_id,
        attend_type: this.isInPost == 1 ? 'Normal' : 'Outside',
        start_time: this.kaoqinInfo.start_time,
        am_end_time: this.kaoqinInfo.am_end_time,
        pm_start_time: this.kaoqinInfo.pm_start_time,
        end_time: this.kaoqinInfo.end_time,
        group_id: this.kaoqinInfo.group_id,
        remark: this.inputValue,
      };

      this.clockStore.setClock(this.clockParams);
      this.modalShow = false
      // console.log('clockParams',this.clockParams);
      
      // #ifdef H5
      uni.navigateTo({
        url: `/pages/workspace/components/fece?isfirstrlsbstatus=${this.isfirstrlsbstatus}`,
      });
      // #endif

      // #ifdef APP-PLUS
      uni.navigateTo({
        url: `/pages/workspace/attendance/face?isfirstrlsbstatus=${this.isfirstrlsbstatus}`
      })
      // #endif

    },
    onClock () {
      const now = new Date().getTime();
      const offTime = new Date(`${this.taday} ${this.kaoqinInfo.end_time}`).getTime();
      const start_clock_time = new Date(`${this.taday} ${this.kaoqinInfo.start_clock_time}`).getTime();
      const end_clock_time = new Date(`${this.taday} ${this.kaoqinInfo.end_clock_time}`).getTime();

      if (this.clock_type == 1 && now < start_clock_time) {
        uni.$u.toast('现在还没有到上午打卡时间');
        return
      }

      if (this.clock_type == 2 && now > end_clock_time) {
        uni.$u.toast('已过下班打卡时间');
        return
      }

      // 外勤
      if (this.isInPost !== 1) {
        this.content = '当前定位不在打卡范围，确认要打卡吗？';
        this.modalShow = true;
        return
      }

      // 是否迟到早退  早退弹框
      if (this.clock_type == 2 && now < offTime) {
        this.content = '未到下班时间，确认立刻打卡吗？';
        this.modalShow = true;
        return
      }
      this.addClock();
    },
    back () {
      uni.switchTab({
        url: '/pages/workspace/home/index',
        animationType: 'pop-in',
        animationDuration: 200
      })
      // uni.navigateBack({ delta: 1 });
    },
    toStatis () {
      uni.navigateTo({
        url: '/pages/workspace/attendance/statis',
        animationType: 'none'
      })
    },
    settingSetUp () {
      uni.navigateTo({
        url: '/pages/workspace/attendance/setup',
        animationType: 'none'
      })
    },
    updateAddressInfo (addressData) {
      this.userPost.address.poiName = addressData.poiName || addressData.address;
      this.addressReady = true; // 标记地址已经准备好
      // 强制更新视图
      this.$forceUpdate();
    },
  },
}
</script>
<script module="mapDom" lang="renderjs">
	// 添加高德安全密钥（不加无法定位）
  // #ifdef APP-PLUS
	window._AMapSecurityConfig = {
		securityJsCode: "6a3b0ae034d75c523abf64e1a334791e"
	};
	import AMapLoader from "@amap/amap-jsapi-loader"
// #endif
	export default {
		data() {
			return {
				map: null,
			}
		},
		methods: {
			dataChange(newValue, oldValue, ownerVm, vm) {
				if (newValue != null || newValue != '' || newValue != undefined) {
					const newData = JSON.parse(newValue);
					this.initMap(newData.kaoqinInfo, newData.userPost)
				}
			},
			initMap(kaoqinInfo, userPost) {
				const that = this;
				AMapLoader.load({
						key: "c9c069d05cb4075e3e24aefea6f77b85", // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ['AMap.Geocoder','AMap.Geolocation'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
					})
					.then((AMap) => {
						that.map = new AMap.Map("map", {
							// 设置地图容器id
							viewMode: "3D", // 是否为3D地图模式
							zoom: 10, // 初始化地图级别
							center: [userPost.long, userPost.lat], // 初始化地图中心点位置 当前人所在位置
						});

            // 创建地理编码器实例
            const geocoder = new AMap.Geocoder({
                city: "全国", // 城市设为全国，默认："010"（北京）
                radius: 500 // 范围，默认：500
            });
            // 获取打卡中心点位置名称
            geocoder.getAddress([userPost.long,  userPost.lat],  function(status, result) {
                 if (status === 'complete' && result.info === 'OK') {
                    const regeocode = result.regeocode;
                    const address = regeocode.formattedAddress;
                    // 优先取更小粒度的字段
                    const building = regeocode.addressComponent.building || '';
                    const neighborhood = regeocode.addressComponent.neighborhood || '';
                    const poiName = building || neighborhood || (regeocode.pois[0]?.name || '');

                    that.$ownerInstance.callMethod('updateAddressInfo', {
                        address,
                        poiName
                    });
                }
            });

						// 打卡区域
						//创建圆形点标记  实例
						var circle = new AMap.Circle({
						  center: [kaoqinInfo.long, kaoqinInfo.lat], //圆心 打卡中心点
						  radius: kaoqinInfo.range, //半径
						  fillOpacity: 0.1, //圆形填充透明度
						  strokeDasharray: [10, 10],
						  fillColor: "#1791fc", //圆形填充颜色
						  zIndex: 50, //圆形的叠加顺序
						});

						//圆形 Circle 对象添加到 Map
						that.map.add(circle);

						// 打卡人当前所在点
						//创建 AMap.Icon 实例：
						const icon = new AMap.Icon({
						  size: new AMap.Size(25, 34), //图标尺寸
						  image: 'https://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png', //Icon 的图像
							imageOffset: new AMap.Pixel(0, 0),
						  imageSize: new AMap.Size(15, 20), //根据所设置的大小拉伸或压缩图片
						});
						// 将 Icon 实例添加到 marker 上:
						const marker = new AMap.Marker({
						  position: new AMap.LngLat(userPost.long, userPost.lat), //点标记的位置 当前人所在位置
						  offset: new AMap.Pixel(-7, -20), //偏移量
						  icon: icon, //添加 Icon 实例
						  zooms: [2, 20], //点标记显示的层级范围，超过范围不显示
						});
						that.map.add(marker);
						//根据覆盖物范围调整视野
						that.map.setFitView([ marker ])

					})
					.catch((e) => {
						console.log(e);
					});
			}
		}
	}
</script>
<style>
#map,
#mapContainer {
  width: 100vw;
  height: 64vh;
}
</style>

<style lang="scss">
page {
  position: relative;
  box-sizing: border-box;
  background-color: #F3F4F5;
}


.zeroLoading {
  top: 38% !important;
}

.relocation {
  position: absolute;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 50%;
  right: 10rpx;
  top: -100rpx;

  image {
    width: 54rpx;
    height: 54rpx;
  }
}

.waiqin-card {
  position: relative;
  /* margin: 0 auto; */
  left: 50%;
  transform: translateX(-50%);
  width: 85%;
  padding: 0.9375rem;
  background-color: #fff;
  border-radius: 0.3125rem;
  z-index: 9;
  /* margin: 29px; */
}

.clock-label {
  font-size: 32rpx;
  font-weight: 500;
  line-height: 52rpx;
}

.clock-address {
  padding-bottom: 8rpx;
  font-size: 24rpx;
  line-height: 52rpx;
  color: #727B82;
}

.clock-timeArea {
  padding-bottom: 16rpx;
  margin-bottom: 2orpx;
  font-size: 24rpx;
  line-height: 52rpx;
  color: #727B82;
  border-bottom: 1rpx solid #E4E5E7;
}

.card {
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 34rpx;
}

.clock-container-top {
  display: flex;
  justify-content: space-between;
}

.clock-onoff-box {
  width: 42%;
  background-color: #EDEDED;
  border-radius: 12rpx;
  padding: 18rpx;

  .clock-time {
    font-size: 26rpx;
    color: #555;
  }

  .clock-msg {
    display: flex;
    margin-top: 14rpx;

    text {
      margin-left: 6rpx;
      font-size: 24rpx;
      color: #999;
    }
  }
}

.tui-modal-custom {
  position: relative;
  text-align: center;

  image {
    width: 100%;
  }

  .success {
    margin-top: 64rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28rpx;
    color: #303030;
  }

  .time {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
  }

  .btn {
    border-top: 1px solid #ddd;
    margin-top: 28rpx;
    padding-top: 20rpx;
    font-weight: 500;
    color: #555;
  }

  .close {
    position: absolute;
    right: -30rpx;
    top: 0;
    z-index: 99999999;
  }
}


.custom-modal {
  text-align: center;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.modal-content {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.modal-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
}

.modal-button {
  width: 50%;
  padding: 15rpx 40rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin: 0 15rpx;
  cursor: pointer;
}

.cancel-button {
  background-color: #f8f8f8;
  color: #666;
  border: 1rpx solid #e5e5e5;
}

.cancel-button:active {
  background-color: #eee;
}

.confirm-button {
  background-color: #5677fc;
  color: #fff;
  border: 1rpx solid #5677fc;
}

.confirm-button:active {
  background-color: #4a6ce8;
}

.error-message {
  text-align: center;
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 5rpx;
  height: 30rpx;
}
</style>
